<template>
  <div class="search">
    <Card>
        <Row class="operation">
          <Button @click="add" type="primary" icon="md-add" v-show="showType=='tree'">添加子部门</Button>
          <Button @click="addRoot" icon="md-add">添加一级部门</Button>
          <Button @click="deleteAll" icon="md-trash">批量删除</Button>
          <Button @click="refresh" :loading="refreshFlag" icon="md-refresh">刷新</Button>
          <Input
            v-model="searchText"
            suffix="ios-search"
            @on-change="onSearch"
            placeholder="输入部门名搜索"
            clearable
            style="width: 250px"
            v-show="showType=='list'"
          />
          <i-switch v-model="strict" size="large" v-show="showType=='tree'" style="margin-left:5px">
            <span slot="open">级联</span>
            <span slot="close">单选</span>
          </i-switch>
          <div style="float: right">
            <RadioGroup v-model="showType" type="button">
              <Radio title="树结构" label="tree">
                <Icon type="md-list"></Icon>
              </Radio>
              <Radio title="列表" label="list">
                <Icon type="ios-apps"></Icon>
              </Radio>
            </RadioGroup>
          </div>
        </Row>
        <Row type="flex" justify="start" v-show="showType=='tree'">
          <Col :md="8" :lg="8" :xl="6">
            <Row>
              <Alert show-icon>
                当前选择编辑：
                <span class="select-title">{{editTitle}}</span>
                <a class="select-clear" v-if="form.id" @click="cancelEdit">取消选择</a>
              </Alert>
              <Input
                v-model="searchText"
                suffix="ios-search"
                @on-change="selectInitTree"
                @on-clear="clearTreeData"
                placeholder="输入部门名搜索"
                clearable
              />
              <div class="tree-bar" :style="{maxHeight: maxHeight}">
                <Tree
                  ref="tree"
                  :data="data"
                  show-checkbox
                  @on-check-change="changeSelect"
                  @on-select-change="selectTree"
                  :check-strictly="!strict"
                ></Tree>
                <Spin size="large" fix v-if="loading"></Spin>
              </div>
            </Row>
          </Col>
          <Col :md="15" :lg="13" :xl="9" style="margin-left: 10px;">
            <Form ref="form" :model="form" :label-width="100" :rules="rules">
              <FormItem label="上级部门" prop="parentId">
                <div style="display: flex">
                  <Input v-model="form.parentName" readonly/>
                  <Poptip transfer trigger="click" placement="right-start" title="选择上级部门" width="250">
                    <Button icon="md-list" style="margin-left:5px;">选择部门</Button>
                    <div slot="content" style="position:relative;min-height:5vh">
                      <Input v-model="searchDeptTitle" placeholder="输入部门名称进行筛选" clearable  @on-clear="clearEditData"
                             suffix="ios-search" @on-change="selectEditTree"/>
                    <Tree :data="editData" ref="editTree" @on-select-change="selectTreeEdit"></Tree>
                    </div>
                  </Poptip>
                </div>
              </FormItem>
              <FormItem label="部门名称" prop="name">
                <Input v-model="form.name" placeholder="输入部门名称"/>
              </FormItem>
              <FormItem label="排序值" prop="sort">
                <Tooltip trigger="hover" placement="right" content="值越小越靠前，支持小数">
                  <InputNumber :max="1000" :min="0" v-model="form.sort"></InputNumber>
                </Tooltip>
              </FormItem>
              <FormItem label="是否启用" prop="status">
                <i-switch size="large" v-model="form.status" :true-value="0" :false-value="1">
                  <span slot="open">启用</span>
                  <span slot="close">禁用</span>
                </i-switch>
              </FormItem>
              <FormItem label="备注" prop="remark">
                <Input v-model="form.remark" type="textarea" :rows="5"/>
              </FormItem>
              <Form-item class="br">
                <Button
                  @click="submitEdit"
                  :loading="submitLoading"
                  type="primary"
                  icon="ios-create-outline"
                >修改并保存</Button>
                <Button @click="handleReset">重置</Button>
              </Form-item>
            </Form>
          </Col>
        </Row>
        <Alert show-icon v-if="showType=='list'">
          已选择
          <span class="select-count">{{selectCount}}</span> 项
          <a class="select-clear" @click="clearSelectAll">清空</a>
        </Alert>
        <Table
          :loading="loading"
          row-key="name"
          border
          :columns="columns"
          :data="data"
          sortable="custom"
          @on-selection-change="showSelect"
          ref="table"
          v-if="showType=='list'"
        ></Table>
    </Card>
    <Modal
      v-model="modalVisible"
      :mask-closable="false"
      width="500px"
      :title="formAddTitle">
      <Form ref="formAdd" :model="formAdd" :label-width="100" :rules="rules">
        <div v-if="showParent">
          <FormItem label="上级部门："><Tag color="green">{{form.title}}</Tag></FormItem>
        </div>
        <FormItem label="部门名称" prop="name">
          <Input v-model="formAdd.name" placeholder="输入部门名称"/>
        </FormItem>
        <FormItem label="排序值" prop="sort">
          <Tooltip trigger="hover" placement="right" content="值越小越靠前，支持小数">
            <InputNumber :max="1000" :min="0" v-model="formAdd.sort"></InputNumber>
          </Tooltip>
        </FormItem>
        <FormItem label="是否启用" prop="status">
          <i-switch size="large" v-model="formAdd.status" :true-value="0" :false-value="1">
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
        <FormItem label="备注" prop="remark">
          <Input v-model="formAdd.remark" type="textarea" :rows="5"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {getDeptTree, searchDept, saveDept, batchDelete, updateDept} from "@/api/dept";

export default {
  name: "Dept",
  data(){
    return{
      maxHeight:"500px",
      total:null,
      loading:false,
      treeLoading:false,
      modalVisible:false,
      data:[],
      searchText:'',
      parentName:'',
      strict:false,
      showParent: false,
      showType: "tree",
      refreshFlag:false,
      editData:[],
      submitLoading:false,
      searchDeptTitle:'',
      selectCount:0,
      form:{},
      editTitle:'',
      selectList:[],
      formAddTitle:'',
      formAdd:{},
      rules:{
        name:[
          {required:true,message:'请输入部门名称',trigger:'blur'}
        ],
        sort:[
          {type:'number',required:true,message:'请填写排序值',trigger:'blur'}
        ]
      },
      columns:[
        {
          type: "selection",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          type: "index",
          width: 60,
          align: "center",
          fixed: "left"
        },
        {
          title: "部门名称",
          key: "name",
          minWidth: 120,
          sortable: true,
          tree: true
        },
        {
          title: "排序",
          key: "sort",
          width: 150,
          sortable: true,
          align: "center",
          sortType: "asc"
        },
        {
          title: "创建时间",
          key: "createTime",
          sortable: true,
          width: 200
        },
        {
          title: "操作",
          key: "action",
          width: 300,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.tableAdd(params.row);
                    }
                  }
                },
                " 添加子部门"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error",
                    size: "small"
                  },
                  on: {
                    click: () => {
                      this.del(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    }
  },
  methods:{
    selectInitTree(){
      searchDept({searchText:this.searchText}).then(res=>{
        if(res.code===200){
          this.treeData=res.data;
        }
      })
    },
    showSelect(v){
      this.selectList=v;
      this.selectCount=v.length;
    },
    selectTree(v){
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.editTitle = data.title;
        this.form = data;
      } else {
        this.cancelEdit();
      }
    },
    clearTreeData(){
      this.form={};
      this.initDeptTree();
    },
    clearSelectAll(){

    },
    cancelAdd(){
      this.modalVisible=false;
    },
    submitAdd(){
      this.$refs['formAdd'].validate((valid)=>{
        if(valid){
          this.submitLoading=true;
          saveDept(this.formAdd).then(res=>{
            if(res.code===200){
               this.$Message.success("操作成功");
            }
            this.submitLoading=false;
            this.modalVisible=false;
            this.initDeptTree();
          })
        }
      })
    },
    add(){
      if(this.form.deptId==null||this.form.deptId==''){
         this.$Message.warning('请先点击选择一个部门');
         return ;
      }
      this.formAddTitle='添加子部门'
      this.showParent=true;
      this.formAdd={
        parentId:this.form.deptId,
        sort:1,
        status:0
      }
      this.modalVisible=true;
    },
    addRoot(){
      this.formAddTitle='添加一级部门';
      this.formAdd={
        parentId:0,
        sort:1,
        status:0
      }
      this.showParent=false;
      this.modalVisible=true;
    },
    del(row){
      this.selectCount = 1;
      this.selectList.push(row);
      this.deleteAll();
    },
    tableAdd(row){
     this.form=row;
     this.add();
    },
    deleteAll(){
      if(this.selectList.length<=0){
         this.$Message.warning("请选择要删除的数据");
         return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content:"您确认要删除所选的 " + this.selectCount + " 条数据及其下级所有数据?",
        loading: true,
        onOk: () => {
          let data=this.selectList;
          let ids='';
          data.forEach(e=>{
            ids+=e.deptId+','
          })
          ids=ids.substring(0,ids.length-1);
          batchDelete(ids).then(res=>{
            if(res.code===200){
              this.$Message.success('操作成功');
            }
            this.selectList = [];
            this.selectCount = 0;
            this.$Modal.remove()
            this.cancelEdit();
            this.init();
          })
        }
      });
    },
    onSearch(){
      if(this.searchText){
        this.loading=true;
        searchDept({searchText:this.searchText}).then(res=>{
          if(res.code===200){
             this.data=res.data;
             this.loading=false
          }
        })
      }else{
        this.initDeptTree();
      }
    },
    changeSelect(v) {
      this.selectCount = v.length;
      this.selectList = v;
    },
    cancelEdit(){
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.deptId;
      this.editTitle = "";
    },
    initDeptTree(){
      getDeptTree().then(res=>{
        if(res.code===200){
          this.data=res.data;
        }
      })
    },
    submitEdit(){
      this.$refs['form'].validate((valid)=>{
        if(valid){
          if (!this.form.deptId) {
            this.$Message.warning("请先点击选择要修改的部门");
            return;
          }
          this.submitLoading=true;
          updateDept(this.form).then(res=>{
            if(res.code===200){
              this.$Message.success('操作成功');
              this.submitLoading=false;
              this.init();
            }
          })
        }
      })
    },
    handleReset(){
      this.$refs.form.resetFields();
    },
    clearEditData(){
      this.form.parentId='';
      this.form.parentName='';
      this.initEditData();
    },
    initEditData(){
      getDeptTree().then(res=>{
        if(res.code===200){
          let first={
            deptId:"0",
            title:'一级部门',
            value:"0"
          }
          res.data.unshift(first);
          this.editData=res.data;
        }
      })
    },
    selectEditTree(){
      searchDept({searchText:this.searchDeptTitle}).then(res=>{
        if(res.code===200){
           this.editData=res.data;
        }
      })
    },
    selectTreeEdit(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.form.parentId = data.deptId;
        this.form.parentName = data.title;
      }
    },
    refresh(){
      let that=this;
      that.refreshFlag=true;
      that.initDeptTree();
      setTimeout(function (){
        that.refreshFlag=false;
      },1000)
    },
    init(){
      this.initDeptTree();
      this.initEditData();
    },
  },
  created(){

  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight;
    this.maxHeight = Number(height - 287) + "px";
    this.init();
  }
}
</script>


<style lang="less">
@import "../../styles/tree-common.less";
</style>
